package com.miguo.framework.web.utils;

import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;

import com.miguo.framework.app.AppFramework;
import com.miguo.framework.utils.Log;

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WebUtils {

    @SuppressWarnings("deprecation")
    public static long getAvailableStorage() {
        String storageDirectory = Environment.getExternalStorageDirectory()
                .toString();
        try {
            StatFs stat = new StatFs(storageDirectory);
            return ((long) stat.getAvailableBlocks() * (long) stat
                    .getBlockSize());
        } catch (RuntimeException localRuntimeException1) {
        }
        return 0;
    }

    public static File getCacheDirectory(Context context) {
        File appCacheDir = null;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            appCacheDir = getExternalCacheDir(context);
        }
        if (appCacheDir == null) {
            appCacheDir = context.getCacheDir();
        }
        return appCacheDir;
    }

    public static File getFileDirectory(Context context) {
        File appCacheDir = null;
        if (appCacheDir == null) {
            appCacheDir = context.getFilesDir();
        }
        if (appCacheDir == null) {
            String cacheDirPath = context.getPackageName() + "/files/";
            appCacheDir = new File(cacheDirPath);
        }
        return appCacheDir;
    }

    public static File getOwnCacheDirectory(Context context, String cacheDir) {
        File appCacheDir = null;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            appCacheDir = new File(Environment.getExternalStorageDirectory(),
                    cacheDir);
        }
        if (!appCacheDir.mkdirs()) {
            appCacheDir = context.getCacheDir();
        }
        return appCacheDir;
    }

    private static File getExternalCacheDir(Context context) {
        File dataDir = new File(new File(
                Environment.getExternalStorageDirectory(), "Android"), "data");
        File appCacheDir = new File(
                new File(dataDir, context.getPackageName()), "cache");
        if (!appCacheDir.exists()) {
            try {
                new File(dataDir, ".nomedia").createNewFile();
            } catch (IOException e) {
                Log.w("Can't create \".nomedia\" file in application external cache directory"
                        + e);
            }
            if (!appCacheDir.mkdirs()) {
                Log.w("Unable to create external cache directory");
                return null;
            }
        }
        return appCacheDir;
    }

    public static boolean isValidURI(String uri) {
        if (uri == null || uri.indexOf(' ') >= 0 || uri.indexOf('\n') >= 0) {
            return false;
        }
        String scheme = Uri.parse(uri).getScheme();
        if (scheme == null) {
            return false;
        }

        // Look for period in a domain but followed by at least a two-char TLD
        // Forget strings that don't have a valid-looking protocol
        int period = uri.indexOf('.');
        if (period >= uri.length() - 2) {
            return false;
        }
        int colon = uri.indexOf(':');
        if (period < 0 && colon < 0) {
            return false;
        }
        if (colon >= 0) {
            if (period < 0 || period > colon) {
                // colon ends the protocol
                for (int i = 0; i < colon; i++) {
                    char c = uri.charAt(i);
                    if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z')) {
                        return false;
                    }
                }
            } else {
                // colon starts the port; crudely look for at least two numbers
                if (colon >= uri.length() - 2) {
                    return false;
                }
                for (int i = colon + 1; i < colon + 3; i++) {
                    char c = uri.charAt(i);
                    if (c < '0' || c > '9') {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    public static boolean isValidURL(String url) {
        String http_regexp = "(http|https|ftp)://([^/:]+)(:\\d*)?([^#\\s]*)";
        Pattern patt = Pattern.compile(http_regexp);
        Matcher matcher = patt.matcher(url);
        boolean isUrl = matcher.matches();
        return isUrl;
    }

    public static boolean isMGUrl(String url) {
        boolean result = false;
        if (!TextUtils.isEmpty(url)) {
            String http_regexp = "^(http://|https://|)([A-Za-z0-9-_.]+.|)(meguo.com|miguo.cn|miguo.com.cn|juduoduo.com)(/.*?|)";
            Pattern pattern = Pattern.compile(http_regexp);
            Matcher matcher = pattern.matcher(url);
            result = matcher.matches();
        }
        return result;
    }

    public static String DefaultUrlParam(String url) {
        if (isMGUrl(url) && !url.contains("platform")) {
            if (url.contains("?")) {
                url = url + "&" + AppFramework.getDefaultUrlParam();
            } else {
                url = url + "?" + AppFramework.getDefaultUrlParam();
            }
        }
        return url;
    }

}
